<template>
  <div class="ai-assistant">
    <div class="header">
      <h1>AI 助手对话页面</h1>
    </div>
    <div class="chat-container">
      <div class="messages" ref="messageContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.sender]"
        >
          <div class="message-content">{{ message.text }}</div>
        </div>
      </div>
      <div class="input-container">
        <input 
          type="text" 
          v-model="userInput" 
          @keydown.enter="sendMessage" 
          placeholder="输入你的问题..."
        />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: "AIAssistant",
  data() {
    return {
      userInput: '',
      messages: []
    };
  },
  methods: {
    async sendMessage() {
      if (this.userInput.trim() === '') {
        return;
      }

      const userMessage = {
        text: this.userInput,
        sender: 'user'
      };
      this.messages.push(userMessage);
      this.scrollToBottom();

      try {
        const response = await axios.post('YOUR_BACKEND_API_ENDPOINT', {
          message: this.userInput
        });

        const aiMessage = {
          text: response.data.reply,
          sender: 'ai'
        };
        this.messages.push(aiMessage);
        this.scrollToBottom();
      } catch (error) {
        console.error("Error communicating with AI backend:", error);
      }

      this.userInput = '';
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        container.scrollTop = container.scrollHeight;
      });
    }
  }
};
</script>

<style scoped>
.ai-assistant {
  display: flex;
  flex-direction: column;
  height: 100vh;
  font-family: Arial, sans-serif;
}

.header {
  background-color: #4CAF50;
  color: white;
  padding: 10px;
  text-align: center;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 20px;
}

.messages {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.message {
  display: flex;
  margin: 10px 0;
}

.message.user {
  justify-content: flex-end;
}

.message.ai {
  justify-content: flex-start;
}

.message-content {
  max-width: 60%;
  padding: 10px;
  border-radius: 10px;
}

.message.user .message-content {
  background-color: #DCF8C6;
}

.message.ai .message-content {
  background-color: #F1F0F0;
}

.input-container {
  display: flex;
  border-top: 1px solid #ccc;
  padding: 10px;
}

input[type="text"] {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 4px;
  margin-right: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
}

button:hover {
  background-color: #45A049;
}
</style>
